<?php
require_once "../config/app.config.php";
class analytics_api
{

    protected $auth;

    public function login($email, $password)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, true);

        $data = array (
        'accountType'=>'GOOGLE',
        'Email'=>$email,
        'Passwd'=>$password,
        'service'=>'analytics',
        'source'=>''
        );

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        $this->auth = '';
        if ($info['http_code'] == 200)
        {
            preg_match('/Auth=(.*)/', $output, $matches);
            if ( isset ($matches[1]))
            {
                $this->auth = $matches[1];
            }
        }

        return $this->auth != '';

    }

    public function call($url)
    {

        $headers = array ("Authorization: GoogleLogin auth=$this->auth");

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if ($info['http_code'] == 200)
        {
            return $output;
        }
        else
        {
            return false;
        }

    }

}


$api = new analytics_api();
if($api->login('tibor.kiray@gmail.com', 'voevitca')) {
    $xml = $api->call('https://www.google.com/analytics/feeds/accounts/default');
    vp($xml);
}
else {
    vp("Login Failed");
}


?>
